"""
serializers
Administrator
2023/12/6
convergence-server
"""
import re
from rest_framework import serializers
from utils.response_util import APIResponse
from system.models import Menus,Image,Message,CurrencyLabel,LabelType
from company.models import Company
from rest_framework.fields import SerializerMethodField
from django.contrib.sites.shortcuts import get_current_site
class MenusSerializer(serializers.ModelSerializer):
    """菜单管理"""
    # menu_childs = PermissionSerializer(many=True, read_only=True)
    # method_name = SerializerMethodField()

    class Meta:
        model = Menus
        fields = ('id', 'parent_id', 'name', 'icon', 'is_menu','href',
                  'frontpath', 'method', 'condition', 'status', 'order')

    def get_method_name(self, obj):
        """获取类型"""
        return obj.get_method_display()

    def create(self, validated_data):
        exist = Menus.objects.filter(name=validated_data['name'], parent_id=validated_data['parent_id']).exists()
        if exist:
            raise serializers.ValidationError('菜单已存在')
        else:
            instance = Menus.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        if not 'is_menu' in validated_data and 'status' in validated_data:
            instance.status = validated_data['status']
            instance.save()
        else:
            if validated_data['is_menu']:
                validated_data.pop("method")
                validated_data.pop("condition")
            else:
                validated_data.pop("frontpath")
                validated_data.pop("icon")
            roles = list(validated_data.pop("role", ''))
            Menus.objects.filter(pk=instance.pk).update(**validated_data)
            if roles:
                instance.role.clear()
                instance.role.add(*roles)
        return instance



class ImageSerializer(serializers.ModelSerializer):
    """图库"""
    http_url = SerializerMethodField()
    class Meta:
            model = Image
            fields = ('id','url','http_url','type')

    def get_http_url(self, obj):
        # current_site = get_current_site(self.context.get('request'))
        # domain_name = current_site.domain
        domain_name = "192.168.3.7:8000"
        return f"http://{domain_name}{obj.url.url}"

class MessageSerializer(serializers.ModelSerializer):
    """消息管理"""

    class Meta:
        model = Message
        fields = ('id','type','title', 'content', 'add_time', 'creator_user')


    def create(self, validated_data):
        validated_data['creator_user'] = self.context['request'].user.id  # 设置 creator_user 值为当前登录用户
        return super().create(validated_data)

class CompanyMessageSerializer(serializers.ModelSerializer):
    """消息管理"""


    company_name = serializers.SerializerMethodField()

    class Meta:
        model = Message
        fields = ('id','type','title', 'content', 'add_time', 'creator_user','company_name')


    def create(self, validated_data):
        validated_data['creator_user'] = self.context['request'].user.id  # 设置 creator_user 值为当前登录用户
        validated_data['company_id'] = self.context['request'].user.company_id  # 设置 creator_user 值为当前登录用户
        return super().create(validated_data)

    def get_company_name(self,obj):
        company = Company.objects.filter(id=obj.company_id).first()
        if company:
            return company.name
        return ''

class LabelTypeSerializer(serializers.ModelSerializer):
    """
    迪：通用标签类型
    """

    class Meta:
        model = LabelType
        fields = ('id', 'name')


class CurrencyLabelSerializer(serializers.ModelSerializer):
    """
    通用标签
    """
    # label_type_name = SerializerMethodField()
    type_name = serializers.CharField(max_length=128, default='',
                                      allow_null=True, write_only=True)

    class Meta:
        model = CurrencyLabel
        # fields = ('id', 'label_type', 'label_type_name', 'name', 'order', 'type_name')
        fields = ('id', 'name', 'order', 'type_name','type')
        # exclude = ['type_name']

    def get_label_type_name(self, obj):
        """获取标签类型"""
        # return obj.label_type.name
        return ''

    def create(self, validated_data):
        label_type_data = validated_data.pop("type_name")
        # if not validated_data.get("label_type") and label_type_data:
        #     obj, created = LabelType.objects.get_or_create(name=label_type_data)
        #     validated_data['label_type'] = obj
        instance = CurrencyLabel.objects.create(**validated_data)
        return instance